package com.webchat.Utils;

import com.webchat.dao.UsersChatRecordsDao;
import com.webchat.dao.UsersFriendDao;
import com.webchat.model.UsersChatRecordsEntity;
import com.webchat.model.UsersEntity;
import com.webchat.model.UsersFriendshipsEntity;
import com.webchat.thread.UserOnlineHandleThread;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONObject;

import javax.websocket.EncodeException;
import javax.websocket.Session;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * Created by YongX on 2016/8/20.
 */
public class SessionUtils {
    public static Map<Integer, Session> clients = new ConcurrentHashMap<Integer, Session>();
    private static Log logger = LogFactory.getLog(SessionUtils.class);
    public static boolean statrTh = false;

    public static void put(Integer uid, Session session){
        clients.put(getKey(uid), session);
        UserOnlineHandleThread.setUserOnlineTime(uid);
        if (statrTh == false){
            logger.info("启动线程中。。");
            new UserOnlineHandleThread().start();
            statrTh= true;
        }
    }

    public static Session get(Integer uid){
        return clients.get(getKey(uid));
    }

    public static void remove(Integer uid){
        logger.info("删除："+uid+"的会话");
        clients.remove(getKey(uid));
    }

    public static boolean hasConnection(Integer uid) {
        return clients.containsKey(getKey(uid));
    }

    public static Integer getKey(Integer uid) {
        return uid;
    }

    public static Integer removeSession(Session session){
        Integer uid = getUidBySession(session);
        if (uid > 0){
            remove(uid);
            return uid;
        }
        return  -1;
    }

    public static Integer getUidBySession(Session session){
        Integer uid = 0;
        for (Map.Entry<Integer, Session> entry : clients.entrySet()) {
            if (entry.getValue().equals(session)){
                uid = entry.getKey();
                logger.info("查找到UID："+uid+" 的会话");
                break;
            }
        }
        return uid;
    }

    public static String sendMessageToUser(Integer uid,Integer accpetUid, String content) throws IOException, EncodeException {
        UsersFriendDao ufDao = new UsersFriendDao();
        if (ufDao.isFriend(uid, accpetUid) == false){
            return "对方不是你的好友无法发送";
        }

        UsersChatRecordsEntity entity = new UsersChatRecordsEntity();
        UsersChatRecordsDao dao = new UsersChatRecordsDao();
        entity.setId(0);
        entity.setUid(accpetUid);
        entity.setFromuid(uid);
        entity.setContent(content);
        entity.setIsRead((byte) 0);
        entity.setCreatedAt(new Timestamp(System.currentTimeMillis()));
        entity.setUpdatedAt(new Timestamp(System.currentTimeMillis()));
        dao.save(entity);
        if (clients.containsKey(accpetUid)){
            sendMessage(accpetUid, uid, content, 1);
        }
        return "OK";
    }

    public static final void sendOnlineMessage(UsersEntity entity)  {
        UsersFriendDao usersFriendDao = new UsersFriendDao();
        List<UsersFriendshipsEntity> usersList = usersFriendDao.getFriendList(entity.getId());
        for (UsersFriendshipsEntity item : usersList){
            if (item.getUid() == entity.getId() && entity.getId() != item.getFriendUid()){
                sendMessage(item.getFriendUid(), 1, entity.userBasicAttributes(), 2);
            }else if (item.getFriendUid() == entity.getId() && entity.getId() != item.getUid()){
                sendMessage(item.getUid(), 1, entity.userBasicAttributes(), 2);
            }
        }
    }

    public static final void sendDisconnectMessage(UsersEntity entity){
        UsersFriendDao usersFriendDao = new UsersFriendDao();
        List<UsersFriendshipsEntity> usersList = usersFriendDao.getFriendList(entity.getId());
        for (UsersFriendshipsEntity item : usersList){
            if (item.getUid() == entity.getId() && entity.getId() != item.getFriendUid()){
                sendMessage(item.getFriendUid(), entity.getId(),entity.userBasicAttributes(), 3);
            }else if (item.getFriendUid() == entity.getId() && entity.getId() != item.getUid()){
                sendMessage(item.getUid(), entity.getId(), entity.userBasicAttributes(), 3);
            }
        }
    }

    private static final void sendMessage(Integer uid, Integer sendUid, String  msg, Integer type) {
        if (clients.containsKey(uid)){
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("type", type);
            JSONObject json = new JSONObject();
            json.put("senduid", sendUid);
            json.put("content", msg);
            jsonObject.put("msg", json);
            logger.info(jsonObject.toString());
            try {
                clients.get(uid).getBasicRemote().sendText(jsonObject.toString());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
